var path = require('path');
var fs = require('fs');
const {exec} = require('child_process');
var os = require('os');

function runWebHook(config) {

  return function (req, res) {
    // if(req.param('token') !== config.authority_token){
    //   res.json({ status: 400, message: "no server" });
    //   return;
    // }
    var scriptFileName = "pulldoc.sh";
    if (os.platform()&&os.platform().startsWith("win")){
      scriptFileName = "pulldoc.bat";
    }
    var file = path.join(config.script_url, scriptFileName);
    console.log("fileName：", file);
    console.log("os：", os.platform());
    fs.exists(file, function (exists) {
      if (exists) {
        try {
          exec(file, (error, stdout, stderr) => {
            if (error) {
              // throw error;
              console.log("[ERROR]  "+error);
              res.json({status: 500, message: "script error"+error});
            } else {
              console.log(stdout);
              res.json({status: 200, message: "ok"});
            }
          });
        } catch (e) {
          res.json({status: 500, message: "script err::" + e.message});
        }

      } else {
        res.json({status: 500, message: "script file not exist"});
      }
    })
  };
}

module.exports = runWebHook;
